<%@ page import="com.lagou.webwork.model.Result" %>
<%@ page import="com.lagou.webwork.model.Student" %>
<%@ page import="java.util.List" %>
<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2021/5/26
  Time: 17:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>学生信息管理系统</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<style>
    .btn:focus,
    .btn:active:focus,
    .btn.active:focus,
    .btn.focus,
    .btn:active.focus,
    .btn.active.focus {
        outline: none;
        border-color: transparent;
        box-shadow: none;
    }
</style>

<body style="padding: 20px;">
<h2>学生信息管理 <a href="classManage.jsp" class="btn btn-link btn-lg">班级管理>>></a></h2>

<form action="" method="POST" role="form" class="form-group form-inline">
    <button type="button" class="btn btn-success" onclick="openAddModal()" data-toggle="modal"
            data-target="#infoModal">新增
    </button>
    <button type="button" class="btn btn-danger" onclick="openDelModal()">删除</button>
    <button type="button" class="btn btn-warning" onclick="openEditModal()">编辑</button>
    <button type="button" class="btn btn-info" onclick="getPagedDataList(1,5)">查询</button>

    <input type="search" name="" id="idSearchInput" class="form-control inline" value="" required="required"
           title="" placeholder="按学号查询">
    <input type="search" name="" id="nameSearchInput" class="form-control form-inline" value="" required="required"
           title="" placeholder="按姓名查询">
</form>

<table class="table table-hover table-responsive table-striped" id="dataTable">
    <thead>
    <tr>
        <th>序号</th>
        <th>学号</th>
        <th>姓名</th>
        <th>所在班级</th>
        <th>性别</th>
        <th>出生日期</th>
        <th>邮箱</th>
        <th>备注</th>
    </tr>
    </thead>
    <tbody>
    </tbody>
</table>
<nav aria-label="Page navigation" class="text-center">
    <div id="Paginator" style="text-align: center">
        <ul id="pageLimit" style="cursor:pointer;"></ul>
    </div>
</nav>

<!-- 新增/编辑弹框 -->
<form role="form" class="form" id="infoForm" onsubmit="return formSubmit();">
    <div class="modal fade" id="infoModal" data-backdrop="static">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="modalTitle">标题</h4>
                    <input type="hidden" name="" id="optionType" class="form-control" value="">

                </div>
                <div class="modal-body">

                    <div class="form-group">
                        <label for="sidInput">学号:</label>
                        <input type="hidden" id="idInput">
                        <input type="text" class="form-control" id="sidInput" placeholder="请输入" required
                               pattern="^[0-9]{4}$" title="请输入4位数字">
                    </div>

                    <div class="form-group">
                        <label for="nameInput">姓名：</label>
                        <input id="nameInput" class="form-control" type="text" name="nameInput" required
                               placeholder="请输入"
                               pattern="^[\u4e00-\u9fa5]{0,5}$" title="请输入5位以内的汉字">
                    </div>

                    <div class="form-group">
                        <label for="classInput">所属班级：</label>
                        <select id="classInput" class="form-control" required>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="sexSelect">性别：</label>
                        <select id="sexSelect" class="form-control" name="">
                            <option selected value="男">男</option>
                            <option value="女">女</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="birthDateInput" class="control-label">出生日期:</label>
                        <input type="date" name="birthDateInput" id="birthDateInput" class="form-control" value=""
                               required
                               title="">
                    </div>

                    <div class="form-group">
                        <label for="emailInput" class="control-label">邮箱:</label>
                        <input type="email" name="emailInput" class="form-control" id="emailInput" placeholder="请输入邮箱">
                    </div>

                    <div class="form-group">
                        <label for="remarkInput" class="control-label">备注:</label>
                        <textarea class="form-control" name="remarkInput" id="remarkInput" style="resize:none;"
                                  rows="5"></textarea>
                    </div>

                    <!-- <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> -->

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="submit" class="btn btn-primary" data-target="infoForm">提交</button>
                    <%--data-target="infoForm"--%>

                </div>
            </div>
        </div>
    </div>
</form>

<!-- 删除弹框 -->
<div class="modal fade" id="delModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">提示信息</h4>
            </div>
            <div class="modal-body">
                确认删除吗？
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="delInfo()">删除</button>
            </div>
        </div>
    </div>
</div>

<!-- 提示-->
<div class="alert alert-danger" id="alterTips"
     style="width:400px;display: none;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);z-index: 99999;">

    <button type="button" class="close" aria-hidden="true" onclick="$('#alterTips').hide();">&times;</button>
    <p> （3秒后自动关闭）</p>
</div>

<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap.help.js"></script>
<script src="js/bootstrap-paginator.min.js"></script>
<script>
    $(function () {

        getClassList();
        getPagedDataList(1, 5);
    });

    function getClassList() {
        $("#classInput").empty();
        let paramsList=[]
        $.ajax({
            url: "/work/getClassList",
            type: "post",
            data: {
                "paramsList": JSON.stringify(paramsList),
                "page": 1,
                "number": 999
            },
            success: function (result) {
                if (result.totalCount == 0) {

                    alertTips("danger", "发生错误，未找到该数据请刷新后再试！");
                    $("#infoModal").modal("hide");
                    return;
                }

                //拿到班级数据 渲染下拉列表
                result.dataList.forEach(element => {
                    let id = element.id;
                    let name = element.name;
                    let grade = element.grade;
                    let insertOption = $(`<option value="\${id}">\${grade} - \${name}</option>`);

                    $("#classInput").append(insertOption);
                });
            }
        })
    }

    function getPagedDataList(page, number) {
        // console.log("我被调用拉,page:"+page+",number:"+number);

        //先清空之前的表格内容
        $("#dataTable tbody").empty();

        let idSearch = $("#idSearchInput").val().trim();
        let nameSearch = $("#nameSearchInput").val().trim();

        function searchParams(key, value) {
            this.key = key;
            this.value = value;
        }

        let paramsList = [];
        if (idSearch) {
            paramsList.push(new searchParams("sid", idSearch));
        }
        if (nameSearch) {
            paramsList.push(new searchParams("name", nameSearch));
        }

        //使用ajax获取接口数据
        $.ajax({
            url: "/work/getStudentList",
            type: "post",
            data: {
                "paramsList": JSON.stringify(paramsList),
                "page": page,
                "number": number
            },
            success: function (result) {
                let totalCount;
                if (result != null && result.dataList != null) {
                    totalCount = result.totalCount;

                    if (result.dataList.length <= 0) {
                        var insertTr = $(`
                            <tr>
                                <td colspan="8" style="text-align:center;font-weight:bold;">
                                    <h5>已经没有数据啦~</h5>
                                </td>
                            </tr>`);
                        $("#dataTable tbody").append(insertTr);
                    } else {
                        //拿到用户数据 渲染表格
                        result.dataList.forEach(element => {
                            console.log(element);
                            let id = element.id;
                            let sid = element.sid;
                            let name = element.name;
                            let sex = element.sex;
                            let birthDate = element.birthDate;
                            let email = element.email;
                            let remark = element.remark;

                            let className = element.className;

                            var insertTr = $(`
                                    <tr>
                                        <td>
                                            <input type="checkbox" value="\${id}" name="selectedChk">
                                        </td>
                                        <td>\${sid}</td>
                                        <td>\${name}</td>
                                        <td>\${className}</td>
                                        <td>\${sex}</td>
                                        <td>\${birthDate}</td>
                                        <td>\${email}</td>
                                        <td>\${remark}</td>
                                    </tr>`);
                            $("#dataTable tbody").append(insertTr);
                        });
                    }
                }
                //判断当前需要跳转的页码大于最大页码，把最大页码赋值给需要跳转的页码
                let totalPage = (totalCount / number);
                if (totalCount % number != 0) {
                    totalPage++;
                }
                if (page > totalPage) {
                    page = totalPage;
                }
                //配置分页插件
                $('#pageLimit').bootstrapPaginator({
                    bootstrapMajorVersion: 3,
                    currentPage: page, // 当前页数
                    numberOfPages: 5, // 显示按钮的数量
                    size: "normal",
                    totalPages: totalPage, // 总页数
                    itemTexts: function (type, page, current) {
                        switch (type) {
                            case "first":
                                return "首页";
                            case "prev":
                                return "上一页";
                            case "next":
                                return "下一页";
                            case "last":
                                return "末页";
                            case "page":
                                return page;
                        }
                    },
                    // 点击事件，用于通过Ajax来刷新整个list列表
                    onPageClicked: function (event, originalEvent, type, page) {
                        getPagedDataList(page, number);
                    }
                });

            }
        });
    }

    /**
     * 改变表格颜色
     * **/
    function changeTableColor() {
        $("#dataTable").find("tbody tr:odd").css("backgroundColor", "#FCF8E3"); //找tbody中的偶数行tr index从0开始,所以先显示下面的颜色
        $("#dataTable").find("tbody tr:even").css("backgroundColor", "#D9EDF7");  //找tbody中的奇数行tr
    }

    /**
     * 打开新增用户窗口
     * **/
    function openAddModal() {
        //调用dom form元素的reset方法对表单内的控件进行清空
        document.getElementById("infoForm").reset();
        $("#modalTitle").text("新增用户");
        $("#optionType").val("add");
    }

    /**
     * 打开编辑用户窗口
     * **/
    function openEditModal() {
        let checkBoxList = getCheckedList();
        //如果列表的长度为0，表示没有点选元素   长度大于1，表示点选多个元素
        if (checkBoxList.length != 1) {
            //弹框提示错误
            alertTips("danger", "请选择且只能选择一条需要编辑的信息！！！");
        } else {
            //调用dom form元素的reset方法对表单内的控件进行清空
            document.getElementById("infoForm").reset();
            $("#infoModal").modal('show');
            $("#modalTitle").text("编辑用户");
            $("#optionType").val("edit");

            getSelectedUser($(checkBoxList[0]).val());
        }
    }

    /**
     * 打开删除提示窗口
     * **/
    function openDelModal() {
        let checkBoxList = getCheckedList();
        //如果列表的长度为0，表示没有点选元素   长度大于1，表示点选多个元素
        if (checkBoxList.length <= 0) {
            alertTips("danger", "请选择需要删除的信息！！！");
        } else {
            $("#delModal").modal("show");
        }
    }

    /**
     * 表单提交方法
     * **/
    function formSubmit() {
        //获取操作类型
        let optionType = $("#optionType").val();

        //新增操作
        if (optionType == 'add') {
            addInfo();
        }

        //编辑操作
        if (optionType == 'edit') {
            editInfo();
        }
        return false;
    }

    /**
     * 新增用户
     * **/
    function addInfo() {
        let studentObj = {
            "sid": $("#sidInput").val(),
            "name": $("#nameInput").val(),
            "sex": $("#sexSelect").find("option:selected").text(),
            "birthDate": $("#birthDateInput").val(),
            "email": $("#emailInput").val(),
            "remark": $("#remarkInput").val(),
            "classId":$("#classInput").val()
        };

        $.ajax({
            url: "/work/addStudent",
            type: "post",
            data: {
                "studentObj": JSON.stringify(studentObj)
            },
            success: function (result) {
                if (result && result.totalCount == 0) {
                    alertTips("danger", result.msg);
                    return;
                }

                //隐藏modal组件
                $("#infoModal").modal("hide");
                reloadTable();
                alertTips("success", result.msg);
            }
        });
    }

    /**
     * 修改用户信息
     **/
    function editInfo() {
        let studentObj = {
            "id": $("#idInput").val(),
            "sid": $("#sidInput").val(),
            "name": $("#nameInput").val(),
            "sex": $("#sexSelect").find("option:selected").text(),
            "birthDate": $("#birthDateInput").val(),
            "email": $("#emailInput").val(),
            "remark": $("#remarkInput").val(),
            "classId":$("#classInput").val()
        };

        $.ajax({
            url: "/work/updateStudent",
            type: "post",
            data: {
                "studentObj": JSON.stringify(studentObj)
            },
            success: function (result) {
                if (result && result.totalCount == 0) {
                    alertTips("danger", result.msg);
                    return;
                }

                //隐藏modal组件
                $("#infoModal").modal("hide");
                reloadTable();
                alertTips("success", result.msg);
            }
        });
    }

    /**
     * 删除用户信息
     * **/
    function delInfo() {
        //获取所有被选中的多选框
        let checkList = getCheckedList();

        //遍历获取被选中的用户的Id
        let selectedIdList = [];
        for (let i = 0; i < checkList.length; i++) {
            selectedIdList.push($(checkList[i]).val());
        }

        $.ajax({
            url: "/work/deleteStudentList",
            type: "post",
            data: {
                "idList": JSON.stringify(selectedIdList)
            },
            success: function (result) {
                if (result && result.totalCount == 0) {
                    alertTips("danger", result.msg);
                    return;
                }

                //隐藏modal组件
                $("#delModal").modal("hide");
                reloadTable();
                alertTips("success", result.msg);
            }
        });
    }

    /**
     * 获取被选中的用户对象
     * **/
    function getSelectedUser(id) {
        let selectedUser = {};

        $.ajax({
            url: "/work/getStudentModel",
            async: false,
            data: {
                "id": id
            },
            success: function (result) {
                if (result.totalCount == 0) {

                    alertTips("danger", "发生错误，未找到该数据请刷新后再试！");
                    $("#infoModal").modal("hide");
                    return;
                }

                let user = result.dataList[0];

                //将选中的数据信息内容 填充到form表单中
                $("#sidInput").val(user.sid);
                $("#idInput").val(user.id);
                $("#nameInput").val(user.name);
                $("#classInput").val(user.classId);
                $("#sexSelect").val(user.sex);
                $("#birthDateInput").val(user.birthDate);
                $("#emailInput").val(user.email);
                $("#remarkInput").val(user.remark);
                return user;
            }
        });
    }



    /**
     * 获取被选中的多选框
     * **/
    function getCheckedList() {
        let checkBoxList = $("#dataTable").find("tr input:checked[name='selectedChk']");  //查找tr中序号选中的多选框元素列表
        return checkBoxList;
    }

    /**
     * 获取当前页数
     * @returns {*|jQuery}
     */
    function getCurrentPage() {
        let currentLink = $('#pageLimit').bootstrapPaginator("getPages");
        return currentLink.current;
    }

    /**
     * 刷新表格数据（页码保留当前）
     */
    function reloadTable() {
        let currentPage = getCurrentPage();

        //清空查询框
        $("#idSearchInput").val("");
        $("#nameSearchInput").val("");

        //调用获取数据接口
        getPagedDataList(currentPage, 5);
        getClassList();
    }

</script>
</body>
</html>
